package com.freewater.library.common.infrastructure.db;

import lombok.AllArgsConstructor;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.EventListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
@Profile({"test", "prod"})
@AllArgsConstructor
public class InitMysqlDb {

    private DataSource dataSource;

    @EventListener(ApplicationReadyEvent.class)
    public void loadData() {
        ResourceDatabasePopulator resourceDatabasePopulator =
                new ResourceDatabasePopulator(false, false, "UTF-8",
                        new ClassPathResource("dbscript/mysql.sql"));
        resourceDatabasePopulator.setSeparator("~~~");
        resourceDatabasePopulator.execute(dataSource);
    }
}
